<template>
  <el-dialog title="SKU管理" :visible.sync="dialogTableVisible">
    <div class="handle-tablle-btn">
      <el-button
        :disabled="!checkStoreIds.length"
        type="text"
        @click="changeBatchStatus(1)"
        >批量启用</el-button
      >
      <el-button
        :disabled="!checkStoreIds.length"
        type="text"
        @click="changeBatchStatus(0)"
        >批量关闭</el-button
      >
      <el-button
        :disabled="!checkStoreIds.length"
        type="text"
        @click="changeBatchPrice"
        >批量设价格</el-button
      >
      <el-button
        :disabled="!checkStoreIds.length"
        type="text"
        @click="changeBatchStock('add')"
        >批量增库存</el-button
      >
      <el-button
        :disabled="!checkStoreIds.length"
        type="text"
        @click="changeBatchStock('reduce')"
        >批量减库存</el-button
      >
    </div>
    <el-form ref="form" :model="form" label-width="100px" size="small">
      <el-table
        :data="form.list"
        @selection-change="handleSelectionChange"
        max-height="480px"
        border
        :header-cell-style="{ 'text-align': 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          property="storeName"
          label="门店名称"
          min-width="120"
        />
        <el-table-column label="规格">
          <template slot-scope="scope">
            {{ String(scope.row.specAttrNameList) }}
          </template>
        </el-table-column>
        <el-table-column label="销售价格（元）">
          <template slot-scope="scope">
            <el-form-item
              :prop="'list.' + scope.$index + '.price'"
              :rules="rules.price"
              label-width="0"
              class="m-t-18"
            >
              <el-input
                v-model.trim="scope.row.price"
                class="w-120"
                placeholder="请输入价格"
                @change="(val) => changeSinglePrice(val, scope.row)"
              />
            </el-form-item> </template
        ></el-table-column>
        <el-table-column label="库存">
          <template slot-scope="scope">
            <el-form-item
              :prop="'list.' + scope.$index + '.inventory'"
              :rules="rules.inventory"
              label-width="0"
              class="m-t-18"
            >
              <el-input
                v-model.trim="scope.row.inventory"
                class="w-120"
                placeholder="请输入数量"
                @change="(val) => changeSingleStock(val, scope.row)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="90" align="center">
          <template slot-scope="scope">
            <el-radio-group
              v-model="scope.row.status"
              @input="changeStatus($event, scope.row)"
            >
              <el-radio :label="1">上架</el-radio>
              <el-radio :label="0">下架</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </el-dialog>
</template>
<script>
import {
  getGoodsStoreList,
  batchModifyStoreSkus,
} from "@/views/wxaMallModule/api/productPublic";
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt,
} from "@/utils/validate";
export default {
  data() {
    // 价格管理
    const validatorPrice = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入价格"));
      } else if (!validateCustomTwoDecimal(value, 7)) {
        callback(new Error("范围0.01~9999999.99"));
      } else {
        callback();
      }
    };
    //  库存管理
    const validatorStockNum = (rule, value, callback) => {
      if (!value) {
        callback();
      } else if (!validateCustomPositiveInt(value, 7)) {
        callback(new Error("范围1~9999999"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        price: [
          {
            required: true,
            validator: validatorPrice,
            trigger: ["blur", "change"],
          },
        ],
        inventory: [
          {
            required: true,
            validator: validatorStockNum,
            trigger: ["blur", "change"],
          },
        ],
      },
      dialogTableVisible: false,
      batchExport: {
        goodId: "",
        skus: [],
      },
      batchExportPriceList: [],
      showExport: false,
      checkStoreIds: [],
      form: {
        list: [],
      },
      goodsId: 0,
    };
  },
  components: {},
  mounted() {
    // this.open();
  },
  methods: {
    open(params) {
      this.goodsId = params.goodsId;
      this.getData();
    },
    getData() {
      let { goodsId } = this;
      getGoodsStoreList({ goodsId }).then((res) => {
        this.batchExport.goodId = goodsId;
        this.dialogTableVisible = true;
        res.data.forEach((v) => {
          v.price = v.price == -1 || !v.price ? 0 / 100 : v.price / 100;
          v.originPrice = v.originPrice / 100;
        });
        this.form.list = res.data;
      });
    },
    handleSelectionChange(e) {
      this.checkStoreIds = e;
    },
    changeBatchStatus(status) {
      let { checkStoreIds, checkStoreId } = this;
      checkStoreId = JSON.parse(JSON.stringify(checkStoreIds));
      checkStoreId.forEach((ele) => {
        ele.status = status;
        ele.price = this.$math.mul(ele.price, 100, 0);
      });
      const params = {
        goodsId: this.goodsId,
        skus: checkStoreId,
      };
      this.upDate(params);
    },
    // 修改价格批量
    changeBatchPrice() {
      const _this = this;
      this.$prompt("请输入销售价格/元", "修改销售价格", {
        confirmButtonText: "保存",
        cancelButtonText: "取消",
        inputValidator: this.validatePrice,
      })
        .then(({ value }) => {
          let { checkStoreIds } = this;
          let checkStoreId = JSON.parse(JSON.stringify(checkStoreIds));
          checkStoreId.forEach((ele) => {
            ele.price = this.$math.mul(value, 100, 0);
          });
          const params = {
            goodsId: this.goodsId,
            skus: checkStoreId,
          };
          this.upDate(params);
        })
        .catch(() => {});
    },
    // 校验价格
    validatePrice(val) {
      console.log(val);
      if (!val) {
        return "请输入价格";
      } else if (!validateCustomTwoDecimal(val, 7)) {
        return "请输入0.01~9999999.99范围金额（小数位不超过2位）";
      }
    },
    validateStock(val) {
      if (!val) {
        return "请输入数量";
      } else if (!validateCustomPositiveInt(val, 6)) {
        return "请输入正整数（最大值999999）";
      }
    },
    changeSinglePrice(value, row) {
      if (!validateCustomTwoDecimal(value, 7)) {
        return;
      }
      let data = JSON.parse(JSON.stringify(row));
      data.price = this.$math.mul(value, 100, 0);
      const params = {
        goodsId: this.goodsId,
        skus: [data],
      };
      this.upDate(params);
    },
    // 修改库存 单个
    changeSingleStock(value, row) {
      if (!validateCustomPositiveInt(value, 7)) {
        return;
      }
      let data = JSON.parse(JSON.stringify(row));
      data.inventory = parseInt(value);
      data.price = this.$math.mul(data.price, 100, 0);
      const params = {
        goodsId: this.goodsId,
        skus: [data],
      };
      this.upDate(params);
    },
    changeStatus(e, row) {
      let data = JSON.parse(JSON.stringify(row));
      data.price = this.$math.mul(data.price, 100, 0);
      const params = {
        goodsId: this.goodsId,
        skus: [data],
      };
      this.upDate(params);
    },
    // 增加库存 批量
    changeBatchStock(mode) {
      const _this = this;
      this.$prompt(
        `请输入${mode === "add" ? "增加" : "减少"}库存数量`,
        `${mode === "add" ? "增加" : "减少"}库存数量`,
        {
          confirmButtonText: "保存",
          cancelButtonText: "取消",
          inputValidator: this.validateStock,
        }
      )
        .then(({ value }) => {
          let { checkStoreIds } = this;
          let checkStoreId = JSON.parse(JSON.stringify(checkStoreIds));
          checkStoreId.forEach((ele) => {
            ele.price = this.$math.mul(ele.price, 100, 0);
            if (mode == "add") {
              ele.inventory =
                ele.inventory + parseInt(value) > 999999
                  ? 999999
                  : ele.inventory + parseInt(value);
            } else {
              ele.inventory =
                ele.inventory - parseInt(value) <= 0
                  ? 0
                  : ele.inventory - parseInt(value);
            }
          });
          const params = {
            goodsId: this.goodsId,
            skus: checkStoreId,
          };
          this.upDate(params);
        })
        .catch(() => {});
    },
    upDate(params) {
      batchModifyStoreSkus(params).then((res) => {
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 2000,
          offset: 40,
        });
        this.checkStoreIds = [];
        this.getData();
      });
    },
  },
};
</script>
<style lang='scss' scoped>
</style>